﻿using MotorLibrary.Error;
using MotorLibrary.Repository;
using MotorLibrary.Repository.DTO;
using System.Collections.Generic;

namespace MotorLibrary.Service
{
    public class EndpointService: IEndpointService
    {
        private IEndpointRepository _endpointRepository;
        private ITipoService _tipoService;

        public EndpointService(IEndpointRepository endpointRepository, ITipoService tipoService)
        {
            this._endpointRepository = endpointRepository;
            this._tipoService = tipoService;
        }

        public EndpointDTO Read(long id)
        {
            return _endpointRepository.Read(id);
        }

        public IList<EndpointDTO> List()
        {
            return _endpointRepository.List();
        }

        private void ChequeaExisteTipo(long tipoID)
        {
            if (_tipoService.Read(tipoID) == null)
                throw new NoEncontradaException(tipoID, "No existe el tipo de endpoint especificado");
        }

        public EndpointDTO Create(EndpointDTO dto)
        {
            ChequeaExisteTipo(dto.TipoID);

            return _endpointRepository.Create(dto);
        }

        public EndpointDTO Update(EndpointDTO dto)
        {
            ChequeaExisteTipo(dto.TipoID);

            return _endpointRepository.Update(dto);
        }

        public EndpointDTO Delete(long id)
        {
            EndpointDTO tmp = _endpointRepository.Read(id);
            if (tmp == null)
            {
                return tmp;
            } else
            {
                tmp.Borrado = true;
                return _endpointRepository.Update(tmp);
            }            
        }

        public IList<EndpointDTO> FilterByTipo(long tipoID)
        {
            return _endpointRepository.Filter(endpoint => endpoint.TipoID == tipoID);
        }

        public IList<EndpointDTO> FilterActivos()
        {
            return _endpointRepository.Filter(endpoint => endpoint.Borrado == false);
        }
    }
}
